import re
import pdfplumber


def extract_chapters(pdf_path):
    # 定义一个字典来存储章节及其内容
    chapters = {}
    current_chapter = None
    current_content = []
    trans_table = str.maketrans('', '', ' \t\n')
    with pdfplumber.open(pdf_path) as pdf:
        for page_num, page in enumerate(pdf.pages, start=1):
            text = page.extract_text()
            if text:
                lines = text.strip().split('\n')
                for line in lines:
                    lines = line.translate(trans_table)
                    if line.endswith("目录"):
                        current_chapter = line
                        continue
                    if re.match(r"第 (\d+) 章 .+", line):
                        # 如果找到新的章节标题，保存当前章节并开始新章节
                        if current_chapter:
                            chapters[current_chapter] = '\n'.join(current_content).strip()
                            current_content = []
                        current_chapter = line.strip()
                    else:
                        # 匹配小节标题
                        section_match = re.match(r"第 (\d+) 节 .+", line)
                        if section_match:
                            # 如果找到小节标题，则将其添加到当前章节
                            chapters[current_chapter].append(line)

                        # 匹配子节标题
                        subsection_match = re.match(r"(\d+\.\d+\.?\d*)\s.*", line)
                        if subsection_match:
                            # 如果找到子节标题，则将其添加到当前章节
                            subsection_number = subsection_match.group(1)
                            chapters[current_chapter].append(line)
                        # 如果当前行不是章节、小节或子节标题，则添加到当前章节的内容中
                        else:
                            if current_chapter not in chapters:
                                chapters[line] = []
                            else:
                                chapters[current_chapter].append(line)
                        # 检查PDF最后一页是否有未保存的章节内容
            if page_num == len(pdf.pages) and current_chapter:
                chapters[current_chapter] = ''.join(current_content).strip()
                # 使用pdfplumber打开PDF文件
    return chapters


pdf_path_sea_ship = '../pdf/全球碳排放市场现状及对我国的启示分析+++中国环境科学学会学术年会论文集+++201512.pdf';
def main():
    pdf_path = 'example.pdf'  # 替换为你的PDF文件路径
    extracted_chapters = extract_chapters(pdf_path_sea_ship)

    # 输出提取到的章节内容
    for chapter_number, content in extracted_chapters.items():
        # print(f"Chapter {chapter_number}:")
        # print(content)
        # print("-" * 50)
        open("../pdf/全球碳排放市场现状及对我国的启示分析+++中国环境科学学会学术年会论文集+++201512.json", 'w').write(''.join(content))


if __name__ == '__main__':
    main()